<?php

declare(strict_types=1);

namespace App\Chat\Controller\Talk;

use App\Chat\Annotation\ChatAuth;
use App\Chat\Controller\ChatBaseController;
use App\Chat\Request\MessageRequest;
use App\Chat\Service\TalkMessageService;
use App\CustHub\Request\RoomBroadcastRequest;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller('ch/chat/message'),ChatAuth]
class MessageController extends ChatBaseController
{
    #[Inject]
    protected TalkMessageService $talkMessageService;

    #[PostMapping('send')]
    public function send(MessageRequest $request)
    {
        $data = $request->all();
        $data['uid'] = $this->uid();
        $data['main_uid'] = Context::get('main_uid');
        $this->talkMessageService->send($data);
        return $this->success();
    }

    /**
     * 发送引用消息
     * @param MessageRequest $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('sendQuoteMsg')]
    public function sendQuoteMsg(MessageRequest $request): \Psr\Http\Message\ResponseInterface
    {
        $data = $request->all();
        $data['uid'] = $this->uid();
        $data['main_uid'] = Context::get('main_uid');
        $this->talkMessageService->sendQuoteMsg($data);
        return $this->success();
    }

    #[PostMapping('text')]
    public function text()
    {
        $params = $this->request->inputs(['talk_type', 'robot_id', 'receiver_id', 'text']);

        $this->validate($params, [
            'talk_type'   => 'required|in:1,2',
            'receiver_id' => 'required|integer|min:1',
            'text'        => 'required|max:65535',
        ]);

        $this->talkMessageService->insertText([
            'talk_type'   => $params['talk_type'],
            'user_id'     => $this->uid(),
            'receiver_id' => $params['receiver_id'],
            'content'     => $params['text'],
            'robot_id' => $params['robot_id']
        ]);

        return $this->success();
    }

    /**
     * 撤回消息
     * @param RoomBroadcastRequest $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('recallMessage')]
    public function recallMessage(RoomBroadcastRequest $request): \Psr\Http\Message\ResponseInterface
    {
        return $this->talkMessageService->recallMessage($request->all()) ? $this->success() : $this->error();
    }
}